<template>
  <div id="desaIndexMap-map" style="width:100%;height:658px;"></div>
</template>
<script>
import '@/assets/map/ol/ol.css';
import { getProjection } from "@/map/projMap.js";
import * as turf from "@turf/turf";
import Map from 'ol/Map';
import View from 'ol/View';
import Point from 'ol/geom/Point';
import LineString from 'ol/geom/LineString';
import Feature from 'ol/Feature';
import Polygon from 'ol/geom/Polygon';
import MultiPolygon from 'ol/geom/MultiPolygon'
import VectorLayer from 'ol/layer/Vector';
import {Vector as VectorSource} from 'ol/source';
import WKT from 'ol/format/WKT';
import {boundingExtent} from 'ol/extent';
import {Fill, Stroke, Style, Icon, Circle as CircleStyle,Text} from 'ol/style';
import dingweiImg from '@/assets/map/image/newImage/blueMarker.png';
import drawPointImg from'@/assets/map/image/fwType/3.png'

export default {
  name: "DesaIndexMap",
  components: {

  },
  props:{
    shpLegendList:{//灾区范围图例列表
      type:Array,
      required:false,
      default: []
    },
    shpDataList: {//灾区范围空间数据列表
      type:Array,
      required:false,
      default: []
    },
    taskDataList: {//任务空间数据列表
      type:Array,
      required:false,
      default: []
    },
    positonGeom: {
      type: String,
      required: true,
      default: ''
    },
    sampleDataList: {//抽样点数据列表
      type:Array,
      required:false,
      default: []
    },
    drawGeom: {//选择的烈度图层
      type: String,
      required: true,
      default: ''
    },
    layerTypeMap: {
      type: Object,
      required: true,
      default: {}
    },
    geomList: {
      type: Array,
      required: true,
      default: () => ([])
    }
  },
  emits:["getMap","closePingGu","outAndInterRing","saveGeom"],
  data() {
    return {
      str: "desaIndexMap",
      map: null,
      center: [105, 34],
      zoom: 4,
      //划定评估子区
      shpLegendArray:[],//灾区范围图例数组
      shpDataArray:[],//灾区范围空间数据列表
      taskDataArray:[],//任务空间数据列表
      sampleDataArray:[],//抽样点数据列表
      shpDataLayer:null,//灾区范围空间数据图层
      taskDataLayer:null,//任务空间数据图层
      positionDataLayer:null,//定位任务空间数据图层
      sampleDataLayer:null,//抽样点数据图层
      tempLayerGeom: '',//临时选择的整图层
      numTime: 1,
      pointList: [],
      addListFeatureAll: [],
      outerRingLinePoint: [],
      interRingLinePoint: [],
      outerRingLine: '',
      InnerRingLine: '',
      featuregeom: null,
      drawPoint: null,
    }
  },
  watch: {
    shpLegendList:{//灾区范围图例列表
      handler: function(newVal,oldVal){
        if(newVal!=oldVal){
          console.log("灾区范围图例列表");
          console.log(newVal);
          this.shpLegendArray = newVal;
        }
      },
      immediate:true
    },
    shpDataList: {//灾区范围空间数据列表
      handler: function(newVal,oldVal){
        console.log("灾区范围空间数据列表");
        console.log(newVal);
        this.shpDataArray = newVal;
        this.showShpDataArray();//显示灾区范围空间数据列表
      },
      immediate:true
    },
    taskDataList: {//任务空间数据列表
      handler: function(newVal,oldVal){
        console.log("任务空间数据列表");
        console.log(newVal);
        this.taskDataArray = newVal;
        setTimeout(() => {
        //显示任务空间数据列表
        this.showTaskDataArray();
      }, 500);
      },
      immediate:true
    },
    positonGeom: {
      handler: function(newVal,oldVal){
        if(newVal != '') {
          this.showTaskPosition(newVal);//显示任务空间数据列表
        }else if(this.positionDataLayer != null){
          this.positionDataLayer.getSource().clear()
        }
      },
      immediate:true
    },
    sampleDataList: {//抽样点数据列表
      handler: function(newVal,oldVal){
        console.log("任务空间数据列表");
        console.log(newVal);
        this.sampleDataArray = newVal;
        this.showSampleDataArray();//显示抽样点数据列表
      },
      immediate:true
    },
    drawGeom: {
      handler: function(newVal,oldVal) {
        // this.drawLiDuLayer(newVal)
      },
      immediate: true
    },
    layerTypeMap: {
      handler: function(newVal,oldVal) {
        this.drawLayerType(newVal)
      },
      immediate: true
    },
    geomList: {
      handler: function(newVal,oldVal) {
        if(newVal.length != 0) {
          this.segmentationPolygon(newVal)
        }
      },
      immediate: true
    }
  },
  created() {

  },
  mounted() {
    console.log("mounted");
    let that = this;
    //地图异步加载
    this.$nextTick(function(){
      console.log('地图异步加载');
      //地图异步加载
      setTimeout(() => {
        //初始化地图信息
        that.initMap();
        //显示灾区范围空间数据列表
        that.showShpDataArray();
        //显示任务空间数据列表
        // that.showTaskDataArray();
        //显示抽样点数据列表
        that.showSampleDataArray();
      }, 200);
    });
  },
  beforeCreate() {//生命周期创建之前
    console.log("beforeCreate");
  },
  beforeMount() {//生命周期挂载之前
    console.log("beforeMount");
  },
  beforeUpdate() {//生命周期更新之前
    console.log("beforeUpdate");
  },
  updated() {//生命周期更新之后
    console.log("updated");
  },
  beforeDestroy() {//生命周期销毁之前
    console.log("beforeDestroy");
  },
  destroyed() {//生命周期销毁完成
    this.map = null;
    console.log("销毁地图");
  },
  activated() {//如果页面有keep-alive缓存功能激活，这个函数会触发
    console.log("activated-"+this.str);
    //自动获取地图div高度
    this.autodivheight();
    //浏览器窗口发生变化时同时变化DIV高度
    window.onresize=this.autodivheight;
  },
  deactivated() {//如果页面有keep-alive缓存功能停用，这个函数会触发
    console.log("deactivated-"+this.str);
    //取消浏览器窗口发生变化时同时变化DIV高度事件
    window.onresize = null;
  },
  methods: {
    initMap() {
      let that = this;
      let mapStr = this.str;
      let targetMap = document.getElementById(mapStr+"-map");
      if(targetMap.innerHTML!=""){
        console.log("清空targetMap");
      }
      targetMap.innerHTML = "";//清空
      //自动获取地图div高度
      this.autodivheight();
      //浏览器窗口发生变化时同时变化DIV高度
      window.onresize=this.autodivheight;
      if(this.map){//避免重复加载地图
        console.log("避免重复加载地图");
        return;
      }
      console.log("初始化地图");
      //获取投影4490坐标系
      this.projection4490 = getProjection();
      //初始化地图信息
      this.map = new Map({
        target: targetMap.id,
        /*controls: defaultControls({attributionOptions: {collapsed: false}})
            .extend([new Logo()]),*/
        view: new View({
          center: this.center,
          maxZoom: 18,
          minZoom: 4,
          zoom: this.zoom,
          constrainResolution:true,//缩放地图可移动到最近的缩放级别（整数zoom级别）
          projection: 'EPSG:4490',
          // resolutions:getResolutions()
        })
      });
      console.log("this.map");
      console.log(this.map);

      //灾区范围空间数据图层
      this.shpDataLayer = new VectorLayer({
        source: new VectorSource({
          wrapX: false
        }),
        projection: 'EPSG:4490'
      });
      this.map.addLayer(this.shpDataLayer);
      this.shpDataLayer.setZIndex(1);

      //任务空间数据图层
      this.taskDataLayer = new VectorLayer({
        source: new VectorSource({
          wrapX: false
        }),
        projection: 'EPSG:4490'
      });
      this.map.addLayer(this.taskDataLayer);
      this.taskDataLayer.setZIndex(1);
      
      //定位任务空间数据图层
      this.positionDataLayer = new VectorLayer({
        source: new VectorSource({
          wrapX: false
        }),
        projection: 'EPSG:4490'
      });
      this.map.addLayer(this.positionDataLayer);
      this.positionDataLayer.setZIndex(1);

      //抽样点数据图层
      this.sampleDataLayer = new VectorLayer({
        source: new VectorSource({
          wrapX: false
        }),
        projection: 'EPSG:4490'
      });
      this.map.addLayer(this.sampleDataLayer);
      this.sampleDataLayer.setZIndex(2);
      this.drawPoint = new VectorLayer({
        source: new VectorSource({
          wrapX: false
        }),
        projection: 'EPSG:4490'
      });
      this.map.addLayer(this.drawPoint);
      this.drawPoint.setZIndex(2);
      //地图对象传递
      this.$emit("getMap",this.map);
      //点击地图事件
      this.map.on('click', function(event){
        let coordinate = that.map.getEventCoordinate(event.originalEvent);
        let pt = turf.point([coordinate[0], coordinate[1]]);
        if(that.layerTypeMap.name == '2点分割'){
          that.jiSuanPoint(pt)
          let style = that.getDrawPointImg()
          let featurePoint = new Point(coordinate)
          let feature = new Feature(featurePoint)
          feature.setStyle(style)
          that.drawPoint.getSource().addFeature(feature)
          if(that.numTime == 2) {
            that.drawPoint.getSource().clear()
            that.$emit('closePingGu','')//重置选择切割方式
            let polyDikuai,polyline
            let sourceList = that.shpDataLayer.getSource().getFeatures()
            if (that.shpDataLayer.getSource().getFeatures()[0].getGeometry().getCoordinates()[0].length == 2) {
              if(that.outerRingLinePoint.length == 0 || that.interRingLinePoint.length == 0) {
                that.$message('两点在同一线上，请重新选择！')
                return
              }
              if (that.layerTypeMap.geom == '') {
                polyDikuai = turf.multiPolygon(sourceList[0].getGeometry().getCoordinates()[0])//被切割的面
              }else{
                polyDikuai = that.featuregeom
              }
              polyline = turf.lineString([that.outerRingLinePoint[0],that.interRingLinePoint[0]]);//切割线
            }else{
              if (that.layerTypeMap.geom == '') {
                polyDikuai = turf.multiPolygon(sourceList[0].getGeometry().getCoordinates()[0])
              }else{
                polyDikuai = that.featuregeom
              }
              polyline = turf.lineString([that.pointList[0],that.pointList[1]]);
            }
            that.$emit('outAndInterRing',[polyDikuai,polyline,that.drawGeom])
            that.numTime = 1
            that.pointList = []
          }else { 
            that.numTime++
          }
        }else if(that.layerTypeMap.name == '4点分割') {
          that.jiSuanPoint(pt)
          let style = that.getDrawPointImg()
          let featurePoint = new Point(coordinate)
          let feature = new Feature(featurePoint)
          feature.setStyle(style)
          that.drawPoint.getSource().addFeature(feature)
          if(that.numTime == 4) {
            that.drawPoint.getSource().clear()
            that.$emit('closePingGu','')
            if(that.outerRingLinePoint.length == 1 || that.interRingLinePoint.length == 1) {
              that.$message('三点在同一线上，请重新选择！')
              return
            }
            console.log("booleanClockwise");
            //外环线
            var outerBoundary = turf.lineSlice(turf.point(that.outerRingLinePoint[0]), turf.point(that.outerRingLinePoint[1]), that.outerRingLine);
            // let residueLineOut = that.pointSegmentationPolygon(that.outerRingLine.geometry.coordinates,outerBoundary.geometry.coordinates)
            // if(outerBoundary.geometry.coordinates.length > residueLineOut.length) {
            //   let temp = outerBoundary.geometry.coordinates
            //   outerBoundary.geometry.coordinates = residueLineOut
            //   residueLineOut = new LineString(temp)
            // }else{
            //   residueLineOut = new LineString(residueLineOut)
            // }
            outerBoundary.geometry.coordinates.push(outerBoundary.geometry.coordinates[0])
            let outIsClockwise = turf.booleanClockwise(outerBoundary)
            outerBoundary.geometry.coordinates.length = outerBoundary.geometry.coordinates.length - 1
            //内环线
            var innerBoundary = turf.lineSlice(turf.point(that.interRingLinePoint[0]), turf.point(that.interRingLinePoint[1]), that.InnerRingLine);
            // let residueLineInner = that.pointSegmentationPolygon(that.InnerRingLine.geometry.coordinates,innerBoundary.geometry.coordinates)
            // if(innerBoundary.geometry.coordinates.length > residueLineInner.length) {
            //   let temp = innerBoundary.geometry.coordinates
            //   innerBoundary.geometry.coordinates = residueLineInner
            //   residueLineInner = new LineString(temp)
            // }else{
            //   residueLineInner = new LineString(residueLineInner)
            // }
             innerBoundary.geometry.coordinates.push(innerBoundary.geometry.coordinates[0])
            let innerIsClockwise = turf.booleanClockwise(innerBoundary)
            innerBoundary.geometry.coordinates.length = innerBoundary.geometry.coordinates.length - 1
            console.log('外：' + outIsClockwise)
            console.log('内：' + innerIsClockwise)
            if(outIsClockwise == false && innerIsClockwise == false) {
              let lineString = that.lockwiseChange(innerBoundary.geometry.coordinates)
              innerBoundary = turf.lineString(lineString);
              that.outerRingLinePoint[0] = outerBoundary.geometry.coordinates[0]
              that.outerRingLinePoint[1] = outerBoundary.geometry.coordinates[outerBoundary.geometry.coordinates.length -1]
              that.interRingLinePoint[0] = innerBoundary.geometry.coordinates[0]
              that.interRingLinePoint[1] = innerBoundary.geometry.coordinates[innerBoundary.geometry.coordinates.length -1]
            }else if(outIsClockwise == true && innerIsClockwise == true) {
              let lineString = that.lockwiseChange(outerBoundary.geometry.coordinates)
              outerBoundary = turf.lineString(lineString);
              that.outerRingLinePoint[0] = outerBoundary.geometry.coordinates[0]
              that.outerRingLinePoint[1] = outerBoundary.geometry.coordinates[outerBoundary.geometry.coordinates.length -1]
              that.interRingLinePoint[0] = innerBoundary.geometry.coordinates[0]
              that.interRingLinePoint[1] = innerBoundary.geometry.coordinates[innerBoundary.geometry.coordinates.length -1]
            }else if(outIsClockwise == true && innerIsClockwise == false) {
              that.outerRingLinePoint[0] = outerBoundary.geometry.coordinates[0]
              that.outerRingLinePoint[1] = outerBoundary.geometry.coordinates[outerBoundary.geometry.coordinates.length -1]
              that.interRingLinePoint[0] = innerBoundary.geometry.coordinates[0]
              that.interRingLinePoint[1] = innerBoundary.geometry.coordinates[innerBoundary.geometry.coordinates.length -1]
            }else if(outIsClockwise == false && innerIsClockwise == true) {
              that.outerRingLinePoint[0] = outerBoundary.geometry.coordinates[0]
              that.outerRingLinePoint[1] = outerBoundary.geometry.coordinates[outerBoundary.geometry.coordinates.length -1]
              that.interRingLinePoint[0] = innerBoundary.geometry.coordinates[0]
              that.interRingLinePoint[1] = innerBoundary.geometry.coordinates[innerBoundary.geometry.coordinates.length -1]
            }
            console.log('外：')
            console.log(that.outerRingLinePoint)
            console.log('内：')
            console.log(that.interRingLinePoint)
            let linString1 = new LineString([that.interRingLinePoint[1],that.outerRingLinePoint[0]])
            let linString2 = new LineString([that.outerRingLinePoint[1],that.interRingLinePoint[0]])
            that.$emit('outAndInterRing',[outerBoundary,innerBoundary,linString1,linString2,that.drawGeom])
          }else{
            that.numTime++
          }
        }
      })
    },
    pointSegmentationPolygon(list1,list2) {
      let resultLine1 = []
      let resultLine2 = []
      for(let i = 0;i < list1.length;i++) {
        if(list1[i] == list2[1]) {
          break
        }else{
          resultLine1.push(list1[i])
        }
      }
      let flag = false
      for(let i = 0;i < list1.length;i++) {
        if(flag) {
          resultLine2.push(list1[i])
        }else{
          if(list1[i] == list2[list2.length - 2]) {
            flag = true
          }
        }
      }
      console.log(resultLine1)
      console.log(resultLine2)
      let line1 = this.lockwiseChange(resultLine1)
      let line2 = this.lockwiseChange(resultLine2)
      let array = []
      for(let i = 0;i < line1.length;i++){
        array.push(line1[i])
      }
      for(let i = 0;i < line2.length;i++){
        array.push(line2[i])
      }
      return array
    },
    lockwiseChange(list) {
      let lineStringList = []
      for(let i = list.length - 1;i > -1;i--) {
        lineStringList.push(list[i])
      }
      return lineStringList
    },
    getPolyonStyle(color){//多边形样式
      let style = new Style({
        fill:new Fill({//填充样式
          color:"rgba(0,0,0,0)"
        }),
        stroke:new Stroke({//描绘
          width:2,//宽
          color:color
        })
      });

      return style;
    },
    getPolyonStyle1(color){//多边形样式
      let style = new Style({
        fill:new Fill({//填充样式
          color:"rgba(0,0,0,0)"
        }),
        stroke:new Stroke({//描绘
          width:2,//宽
          color:color,
          lineDash: [5,10]
        })
      });

      return style;
    },
    getLineStringStyle(color){//线样式
      let style = new Style({
        fill:new Fill({//填充样式
          color:"rgba(0,0,0,0)"
        }),
        stroke:new Stroke({//线
          width:2,//宽
          color:color
        })
      });

      return style;
    },
    jiSuanPoint(pt) {//根据地图点击的点 计算距离内环和外环最近的点
      let outerRing = []
      let InnerRing = []
      let cricle = []
      let point
      let sourceList = this.shpDataLayer.getSource().getFeatures()
      let featureList = sourceList[0].getGeometry().getCoordinates()[0];
      if (featureList.length == 2) {
        outerRing = featureList[0]
        InnerRing = featureList[1]
        outerRing.length = featureList[0].length - 1
        InnerRing.length = featureList[1].length - 1
        this.outerRingLine = turf.lineString(outerRing)
        this.InnerRingLine = turf.lineString(InnerRing)
        let outerRingPoint = turf.nearestPointOnLine(this.outerRingLine, pt, {units: 'miles'});
        let InnerRingPoint = turf.nearestPointOnLine(this.InnerRingLine, pt, {units: 'miles'});
        let num = outerRingPoint.properties.dist.toFixed(0) - InnerRingPoint.properties.dist.toFixed(0)
        if(num > 0) {
          point = new Point([InnerRingPoint.geometry.coordinates[0],InnerRingPoint.geometry.coordinates[1]])
          this.interRingLinePoint.push(point.getCoordinates())
        }else{
          point = new Point([outerRingPoint.geometry.coordinates[0],outerRingPoint.geometry.coordinates[1]])
          this.outerRingLinePoint.push(point.getCoordinates())
        }
      }else{
        cricle = featureList[0]
        cricle.length = featureList[0].length - 1
        let criclePoint = turf.nearestPointOnLine(turf.lineString(cricle), pt, {units: 'miles'});
        point = new Point([criclePoint.geometry.coordinates[0],criclePoint.geometry.coordinates[1]])
        this.pointList.push(point.getCoordinates())
      }
    },
    drawLayerTypeFeature(list) {//添加整个烈度圈任务区域
      let allCoordinates = [];
      for(let i=0;i<list.length;i++){
        let style = this.getPolyonStyle("orange",null,2);
        let xstmId = list[i].xstmId;//ID
        let geomText = list[i].geom;//空间数据
        if(geomText!=null && geomText!="" && geomText!="POLYGON EMPTY"){
          //空间数据
          let featureTmp = new WKT().readFeature(geomText);
          //设置属性
          featureTmp.setProperties({
            type:"draw",//类型
            xstmId:xstmId
          });
          featureTmp.setStyle(style);
          //添加矢量数据
          this.taskDataLayer.getSource().addFeature(featureTmp);
          //获取范围
          let extent = featureTmp.getGeometry().getExtent();
          if(extent.length==4){
            //全部经纬度--左下角
            allCoordinates.push([extent[0],extent[1]]);
            //全部经纬度--右上角
            allCoordinates.push([extent[2],extent[3]]);
          }
        }
      }
      this.showBoundingExtent(allCoordinates);//缩放到区域位置
    },
    drawUtil() {//移除选择的烈度圈
      let sourceList = this.taskDataLayer.getSource().getFeatures()
      for(let i = 0;i < sourceList.length; i++) {
        let wkt = new WKT().writeFeature(sourceList[i],{
          "dataProjection": 'EPSG:4326',
          "featureProjection": 'EPSG:4326'
        })
        if(wkt == this.tempLayerGeom.geom) {
          this.taskDataLayer.getSource().removeFeature(sourceList[i])
        }
      }
    },
    deleteListFeature() {//移除添加的任务区域
      if(this.addListFeatureAll.length != 0) {
        let sourceList = this.taskDataLayer.getSource().getFeatures()
        for(let i = 0;i < sourceList.length; i++) {
          for(let j = 0;j < this.addListFeatureAll.length;j++) {
            if(sourceList[i] == this.addListFeatureAll[j]) {
              this.taskDataLayer.getSource().removeFeature(sourceList[i])
            }
          }
        }
      }
    },
    async drawLayerType(type) {//切割方式的逻辑处理
      if(type.name == '' && this.drawGeom != '') {
        this.drawFeature([this.drawGeom])
        this.drawUtil()
      }else if(type.name == '' && this.drawGeom == '') {
        this.$emit('outAndInterRing',[false])
        this.deleteListFeature()
        this.drawUtil()
      }else if(type.name == '整图层') {
        // this.shpDataLayer.getSource().clear()
        this.tempLayerGeom = this.drawGeom
        this.drawLayerTypeFeature([this.drawGeom])
        this.deleteListFeature()
        this.$emit('outAndInterRing',[false])
      }else if(type.name == '2点分割') {
        if(type.geom.length != 0) {
          this.featuregeom = await this.segmentationUtil(type.geom,this.drawGeom.geom)//获取烈度圈没有被创建的区域的空间数据
        }
        this.$emit('outAndInterRing',[false])
        this.pointList = []
        this.outerRingLinePoint = []
        this.interRingLinePoint = []
        this.numTime = 1
        this.shpDataLayer.getSource().clear()
        this.drawUtil()
        this.drawFeature([this.drawGeom])
        this.deleteListFeature()
      }else if(type.name == '4点分割') {
        this.outerRingLinePoint = []
        this.interRingLinePoint = []
        this.numTime = 1
        this.shpDataLayer.getSource().clear()
        this.drawUtil()
        this.drawFeature([this.drawGeom])
        this.deleteListFeature()
        this.$emit('outAndInterRing',[false])
      }else if(type.name == 'change') {
        this.$emit('outAndInterRing',[false])
      }else if(type.name == '剩余图层') {
        this.$emit('outAndInterRing',[false])
        this.deleteListFeature()
        // this.shpDataLayer.getSource().clear()
        let turfFeature = await this.segmentationUtil(type.geom,this.drawGeom.geom)
        let feature
        if(turfFeature.geometry.type == 'Polygon') {
          feature = new Feature({
            geometry: new Polygon(turfFeature.geometry.coordinates)
          })
        }else{
          feature = new Feature({
            geometry: new MultiPolygon(turfFeature.geometry.coordinates)
          })
        }
        feature.setProperties({
          type:"draw",//类型
          xstmId: this.drawGeom.xstmId
        });
        feature.setStyle(this.getLineStringStyle('blue'))
        this.addListFeatureAll.push(feature)
        // this.polygonCutPolygon(feature.getGeometry().getCoordinates())
        this.taskDataLayer.getSource().addFeature(feature);
      }
    },
    polygonCut(poly, line) {// 线切割面或多面
      console.log('1、进入切方法：')
      let tolerance = 0.000001
      let toleranceType = 'kilometers'
      // 2. 计算交点，并把线的点合并
      //计算相交点
      // let lineIntersect = turf.lineIntersect(line, poly);
      //获取一个或一组Feature，并将所有位置作为点返回。拆分为点
      // const lineExp = turf.explode(line);
      // for (let i = 0; i < lineExp.features.length - 1; i++) {
      //   lineIntersect.features.push(turf.point(lineExp.features[i].geometry.coordinates));
      // }
      // 3. 计算线的缓冲区
      const lineBuffer = turf.buffer(line, tolerance, {
        units: toleranceType,
      });
      console.log('2、计算线的缓冲区!')
      // 4. 计算线缓冲和多边形的difference，返回"MultiPolygon"，所以将其拆开
      //通过从第一个多边形剪裁第二个多边形来查找两个多边形之间的差异。
      const _body = turf.difference(poly, lineBuffer);
      let pieces = [];
      if (_body.geometry.type === 'Polygon') {
        pieces.push(turf.polygon(_body.geometry.coordinates));
      } else {
        _body.geometry.coordinates.forEach(function (a) {
          pieces.push(turf.polygon(a));
        });
      }
      console.log('3、计算线缓冲和多边形的difference!')
      // 5. 处理点数据
      for (let p = 0; p < pieces.length; p++) {
        const piece = pieces[p];
        for (let c in piece.geometry.coordinates[0]) {
          const coord = piece.geometry.coordinates[0][c];
          const p = turf.point(coord);
          // for (let lp in lineIntersect.features) {
          //   const lpoint = lineIntersect.features[lp];
          //   //判断两点距离
          //   if (turf.distance(lpoint, p, toleranceType) <= tolerance * 2) {
          //     piece.geometry.coordinates[0][c] = lpoint.geometry.coordinates;
          //   }
          // }
        }
      }
      console.log('4、处理点数据!')
      //获取一个或多个Feature并创建一个FeatureCollection。
      return turf.featureCollection(pieces);
    },
    polygonCutPolygon(pointslist) {//面切割面或多面
      let splitResult = []
      let polyDikuai = turf.multiPolygon(pointslist)
      let polygon1 = new WKT().readFeature(this.drawGeom.geom)
      var polyDraw = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]]);
      polyDraw.geometry.coordinates = polygon1.getGeometry().getCoordinates()
      let intersection = turf.intersect(polyDraw,polyDikuai);
      let difference1 = turf.difference(polyDraw,polyDikuai)
      // let contains = turf.booleanContains(polyDraw,polyDikuai);
      let intersectionArray = intersection.geometry ? intersection.geometry.coordinates : [];
      let differenceArray = difference1.geometry ? difference1.geometry.coordinates : [];
      splitResult.push(intersectionArray);
      if (differenceArray && differenceArray.length > 1) {
        for (let item of differenceArray) {
          splitResult.push(item);
        }
      } else {
        splitResult.push(differenceArray);
      }
      if (intersection && splitResult.length > 0) {
        for (let item in splitResult) {
          let featureResult = new Feature({
            geometry: new Polygon(splitResult[item] || []),
          });
          featureResult.setStyle(
            new Style({
              //填充色
              fill: new Fill({
                color: 'rgba(244, 3, 49, 0.5)',
              }),
              //边线颜色
              stroke: new Stroke({
                color: '#f40331',
                width: 2,
              }),
            }),
          )
          this.addListFeatureAll.push(featureResult)
          this.taskDataLayer.getSource().addFeature(featureResult);
        }
      }
    },
    async segmentationUtil(smallPolygon,bigPolygon) {//根据已经新建的任务区域切割剩余部分
      let data = null
      let polygon2 = null
      if(smallPolygon.length == 1) {
        let polygon = new WKT().readFeature(smallPolygon[0])
        polygon2 = turf.polygon([[[128, -26],[141, -26],[141, -21],[128, -21],[128, -26]]]);
        polygon2.geometry.coordinates = polygon.getGeometry().getCoordinates()
      }else if(smallPolygon.length == 2) {
        let geom1 = new WKT().readFeature(smallPolygon[0])
        let poly1 = turf.polygon([[[128, -26],[141, -26],[141, -21],[128, -21],[128, -26]]]);
        poly1.geometry.coordinates = geom1.getGeometry().getCoordinates()
        let geom2 = new WKT().readFeature(smallPolygon[1])
        let poly2 = turf.polygon([[[128, -26],[141, -26],[141, -21],[128, -21],[128, -26]]]);
        poly2.geometry.coordinates = geom2.getGeometry().getCoordinates()
        polygon2 = turf.union(poly1, poly2);
      }else{
        let list = smallPolygon
        let multiPolygon,arr
        jump:for(let i = 0;i < list.length;i++) {
          for(let j = 1;j < list.length;j++) {
            console.log('测试' + j)
            let geomText1 = new WKT().readFeature(list[i])
            let a = geomText1.getGeometry().getType()
            let poly1
            if(geomText1.getGeometry().getType() == 'MultiPolygon') {
              poly1 = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]]);
            }else{
              poly1 = turf.polygon([[[128, -26],[141, -26],[141, -21],[128, -21],[128, -26]]]);
            }
            poly1.geometry.coordinates = geomText1.getGeometry().getCoordinates()
            let geomText2 = new WKT().readFeature(list[j])
            let poly2
            if(geomText2.getGeometry().getType() == 'MultiPolygon') {
              poly2 = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]]);
            }else{
              poly2 = turf.polygon([[[128, -26],[141, -26],[141, -21],[128, -21],[128, -26]]]);
            }
            poly2.geometry.coordinates = geomText2.getGeometry().getCoordinates()
            let flag = turf.booleanDisjoint(poly1, poly2)
            if(flag == false) {
              multiPolygon = turf.union(poly1, poly2);
              arr = list.filter(item => item != list[j])
              arr = arr.filter(item => item != list[i])
              break jump
            }
          }
        }
        polygon2 = await this.multiPolygonUtil(multiPolygon,arr)
      }
      let polygon1 = new WKT().readFeature(bigPolygon)
      var polygon3 = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]]);
      polygon3.geometry.coordinates = polygon1.getGeometry().getCoordinates()
      var difference = turf.difference(polygon3,polygon2);
      let feature = new Feature({
        geometry: new Polygon(difference.geometry.coordinates)
      })
      feature.setProperties({
        type:"draw",//类型
        xstmId: this.drawGeom.xstmId
      });
      feature.setStyle(this.getLineStringStyle('blue'))
      this.addListFeatureAll.push(feature)
      // if(type == 'feature') {
      //   data = feature
      // }else{
        data = difference
      // }
      return data

    },
    segmentationPolygon(list) {
      let countGeom = new WKT().readFeature(this.shpDataList[0].geom)
      let countCoor = countGeom.getGeometry().getCoordinates()[0]
      for(let i = 1;i < this.shpDataList.length;i++){
        let geomText1 = new WKT().readFeature(this.shpDataList[i].geom)
        let coor = geomText1.getGeometry().getCoordinates()[0]
        for(let j = 0;j <coor.length;j++) {
          countCoor.push(coor[j])
        }
      }
      countGeom.getGeometry().setCoordinates([countCoor])
      let style = this.getPolyonStyle('red','red',1)
      countGeom.setStyle(style);
      // this.shpDataLayer.getSource().addFeature(countGeom);
      
      let center = turf.point([this.shpDataList[0].longitude,this.shpDataList[0].latitude]);
      let bearing1 = this.shpDataList[0].angle
      let count = parseInt(360 / list.length)
      let bearing2 = bearing1 + count
      let f40331 = this.shpDataList.find(item => item.intensity == 6)
      var radius = f40331.shortY / 2;
      let featureList = []
      for(let i = 0;i < list.length;i++) {
        let sector
        let polyDikuai = turf.polygon([new WKT().readFeature(f40331.geom).getGeometry().getCoordinates()[0][0]])//被切割的面
        
        if( i == 0) {
        }else if(i == list.length - 1){
          bearing1 = bearing2
          bearing2 = bearing1 + count
          let num = bearing2 + count
          if( num > 360 + this.shpDataList[0].angle) {
            bearing2 = 360 + this.shpDataList[0].angle
          }
        }else if(i == list.length - 2){
          bearing1 = bearing2
          bearing2 = bearing1 + count
        }else{
          bearing1 = bearing2
          bearing2 = bearing1 + count
        }
        if(list.length != 3) {
          sector = turf.sector(center, radius, bearing1, bearing2,{units: 'miles',steps: 21});
        }else{
          sector = turf.sector(center, radius, bearing1, bearing2,{units: 'miles',steps: 20});
        }
        featureList.push(turf.intersect(sector, polyDikuai))
        let countGeom = new WKT().readFeature(this.shpDataList[0].geom)
        countGeom.getGeometry().setCoordinates([turf.intersect(sector, polyDikuai).geometry.coordinates])
        let style = this.getPolyonStyle('red','red',1)
        countGeom.setStyle(style);
        // this.shpDataLayer.getSource().addFeature(countGeom);
      }
      this.$emit('saveGeom',featureList)
    },
    multiPolygonUtil(polygon2,list) {//递归进行面与烈度圈的切割
      let multiPolygon
      let arr = []
      jump:for(let i = 0;i < list.length;i++) {
        if(list[i] != undefined) {
          let geomText1 = new WKT().readFeature(list[i])
          let poly1 = turf.polygon([[[128, -26],[141, -26],[141, -21],[128, -21],[128, -26]]]);
          poly1.geometry.coordinates = geomText1.getGeometry().getCoordinates()
          let flag = turf.booleanDisjoint(polygon2, poly1)
          if(flag == false) {
            multiPolygon = turf.union(polygon2, poly1);
            arr = list.filter(item => item != list[i])
            break jump
          }
          if(list.length == 1 && flag == true) {
            multiPolygon = turf.union(polygon2, poly1);
            arr = list.filter(item => item != list[i])
            break jump
          }
        }
      }
      if(arr.length != 0) {
        multiPolygon = this.multiPolygonUtil(multiPolygon,arr)
      }
      return multiPolygon
    },
    drawLiDuLayer(drawLiDuLayer) {//烈度选择并加载
      if(JSON.stringify(this.layerTypeMap) != '{}') {
        this.drawUtil()
      }
      if(drawLiDuLayer == '') {
        this.drawFeature(this.shpDataArray)
      }else{
        this.shpDataLayer.getSource().clear()
        this.drawFeature([drawLiDuLayer])
      }
    },
    drawFeature(list) {//绘制所选择的烈度圈
      let allCoordinates = [];
      for(let i = 0; i < list.length; i++){
        let intensity = list[i].intensity;//烈度
        //获取烈度获取图例序号
        let legendIndex = this.getLegendIndexByValue(intensity);
        let fillColor = this.shpLegendArray[legendIndex].color;
        let intensityStr = this.shpLegendArray[legendIndex].name;
        let style = this.getPolyonTextStyle("rgb(152,152,152)", fillColor, intensityStr);
        let geomText = list[i].geom;//空间数据
        if(geomText!=null && geomText!="" && geomText!="POLYGON EMPTY"){
          //空间数据
          let featureTmp = new WKT().readFeature(geomText);
          //设置属性
          featureTmp.setProperties({
            type:"zqfw",//类型
          });
          featureTmp.setStyle(style);
          //添加矢量数据
          this.shpDataLayer.getSource().addFeature(featureTmp);
          //获取范围
          let extent = featureTmp.getGeometry().getExtent();
          if(extent.length==4){
            //全部经纬度--左下角
            allCoordinates.push([extent[0],extent[1]]);
            //全部经纬度--右上角
            allCoordinates.push([extent[2],extent[3]]);
          }
        }
      }
      this.showBoundingExtent(allCoordinates);//缩放到区域位置
    },
    autodivheight() {//自动获取div高度
      //获取浏览器窗口高度
      let winHeight = 0;
      if (window.innerHeight) {
        winHeight = window.innerHeight;
      } else if ((document.body) && (document.body.clientHeight)) {
        winHeight = document.body.clientHeight;
      }
      //通过深入Document内部对body进行检测，获取浏览器窗口高度
      if (document.documentElement && document.documentElement.clientHeight) {
        winHeight = document.documentElement.clientHeight;
      }
      //全屏时窗口高度:864px,地图div高度:754px
      let tempHeight = 864;
      let mapTempHeight = 754;
      let mapHeight = winHeight - tempHeight + mapTempHeight;
      //最小高度
      if(mapHeight<480){
        mapHeight = 480;
      }
      //设置地图高度
      document.getElementById(this.str+"-map").style.height= mapHeight +"px";
      console.log("窗口高度："+winHeight+"地图高度："+mapHeight);
      //resize事件--刷新地图,确保地图不变形
      if(this.map){
        this.map.updateSize();
        console.log("resize事件--刷新地图,确保地图不变形");
      }
    },
    getDrawPointImg(){// 点图标样式
      let style = new Style({
        image: new Icon({
          src: drawPointImg,
          // anchor: [0.5, 1]
          anchor: [0.5, 0.8]
        }),
      });
      return style;
    },
    getPointImgStyle(){// 点图标样式
      let style = new Style({
        image: new Icon({
          src: dingweiImg,
          // anchor: [0.5, 1]
          anchor: [0.5, 0.8]
        }),
      });
      return style;
    },
    getPointStyle(color,fillColor){// 点样式
      let style = new Style({
        image: new CircleStyle({
          radius:5,
          fill:new Fill({//填充样式
            color:fillColor
          }),
          stroke:new Stroke({//描绘
            width:1,//宽
            color:color
          }),
        }),
      });
      return style;
    },
    getPolyonStyle(color,fillColor,width){//多边形样式
      if(fillColor!=null){
        //填充样式
      }else{
        fillColor = "rgba(0,0,0,0)";
      }
      if(width!=null){
        //线宽度
      }else{
        width = 2;
      }
      let style = new Style({
        fill:new Fill({//填充样式
          color:"rgba(0,0,0,0)"
        }),
        stroke:new Stroke({//描绘
          width:width,//宽
          color:color
        })
      });
      return style;
    },
    getPolyonTextStyle(color,backgroundColor,text){//多边形文字样式
      if(backgroundColor==null){
        backgroundColor = "rgba(0,0,0,0)";
      }
      let style = new Style({
        fill:new Fill({//填充样式
          color:backgroundColor
        }),
        stroke:new Stroke({//描绘
          width:1,//宽
          color:color
        }),
        text: new Text({
          text: text,
          fill: new Fill({
            color: 'black'
          }),
          offsetY:20,
          font:'bold 14px 微软雅黑',
        })
      });

      return style;
    },
    getSelectPolyonStyle(){//选中要素样式
      let style = new Style({
        fill:new Fill({//填充样式
          color:"rgba(255,255,255,0.2)"
        }),
        stroke:new Stroke({//描绘
          width:2,//宽
          color:"rgba(30,144,255,1)"
        })
      });
      return style;
    },
    showBoundingExtent(coordinates){//缩放到区域位置
      console.log("缩放到区域位置");
      if (coordinates!=null && coordinates.length > 1) {
        const extent = boundingExtent(coordinates);
        //this.map.getView().fit(extent, {duration: 1000, padding: [50, 50, 50, 50]});
        this.map.getView().fit(extent, {padding: [50, 50, 50, 50]});
        //获取默认位置
        this.center = this.map.getView().getCenter();
        this.zoom = this.map.getView().getZoom();
      }
    },
    //获取烈度获取填充颜色
    getFillColorByValue(val){
      let fillColor = null;
      if(val && this.shpLegendArray && this.shpLegendArray.length>0){
        for(let i=0;i<this.shpLegendArray.length;i++){
          if(this.shpLegendArray[i].value==val){
            fillColor = this.shpLegendArray[i].color;
            break;
          }
        }
      }

      return fillColor;
    },
    //获取烈度获取图例序号
    getLegendIndexByValue(val){
      let index = null;
      if(val && this.shpLegendArray && this.shpLegendArray.length>0){
        for(let i=0;i<this.shpLegendArray.length;i++){
          if(this.shpLegendArray[i].value==val){
            index = i;
            break;
          }
        }
      }

      return index;
    },
    showShpDataArray(){//显示灾区范围空间数据列表
      let xLong = 0
      let yShort = 0
      let angle = 0
      if(this.shpDataLayer!=null){
        this.shpDataLayer.getSource().clear();//清空
        let list = this.shpDataArray;
        if(list!=null && list.length>0){
          angle = list[0].angle
          //全部经纬度
          let allCoordinates = [];
          for(let i=0;i<list.length;i++){
            xLong += list[i].longX
            yShort += list[i].shortY
            let intensity = list[i].intensity;//烈度
            //获取烈度获取图例序号
            let legendIndex = this.getLegendIndexByValue(intensity);
            if(legendIndex>=0){
              // let fillColor = this.getFillColorByValue(intensity);//获取烈度获取填充颜色
              let fillColor = this.shpLegendArray[legendIndex].color;
              let intensityStr = this.shpLegendArray[legendIndex].name;
              // let style = this.getPolyonStyle("rgba(255,255,255,0.7)",fillColor,0.5);
              //样式
              let style = this.getPolyonTextStyle("rgb(152,152,152)", fillColor, intensityStr);
              let geomText = list[i].geom;//空间数据
              if(geomText!=null && geomText!="" && geomText!="POLYGON EMPTY"){
                //空间数据
                let featureTmp = new WKT().readFeature(geomText);
                //设置属性
                featureTmp.setProperties({
                  type:"zqfw",//类型
                });
                featureTmp.setStyle(style);
                //添加矢量数据
                this.shpDataLayer.getSource().addFeature(featureTmp);
                //获取范围
                let extent = featureTmp.getGeometry().getExtent();
                if(extent.length==4){
                  //全部经纬度--左下角
                  allCoordinates.push([extent[0],extent[1]]);
                  //全部经纬度--右上角
                  allCoordinates.push([extent[2],extent[3]]);
                }
              }
            }
          }
          let that = this;
          let lineString = this.shpDataArray.find(item => item.intensity == '6');
          let options = {units: 'kilometers'};
          let f40331 = this.shpDataList.find(item => item.intensity == 6)
          let point = turf.point([lineString.longitude, lineString.latitude]);
          let distanceX = f40331.longX;
          let bearing = angle;
          
          let destinationX1 = turf.destination(point, distanceX, bearing, options);
          let destinationX2 = turf.destination(point, distanceX, bearing + 180, options);
          let xLine = new LineString([destinationX1.geometry.coordinates,destinationX2.geometry.coordinates])
          // let feature = new Feature(new LineString([destinationX1.geometry.coordinates,destinationX2.geometry.coordinates]))
          let feature = new Feature(new LineString([destinationX2.geometry.coordinates,[lineString.longitude, lineString.latitude],destinationX1.geometry.coordinates]))
          let style = this.getLineStringStyle('#C5C5C6')
          feature.setStyle(style)
          this.shpDataLayer.getSource().addFeature(feature);
          // yShort
          let distanceY = f40331.shortY;
          let destinationY1 = turf.destination(point, distanceY, bearing + 90, options);
          let destinationY2 = turf.destination(point, distanceY, bearing + 270, options);
          // let feature1 = new Feature(new LineString([destinationY1.geometry.coordinates,destinationY2.geometry.coordinates]))
          let feature1 = new Feature(new LineString([destinationY2.geometry.coordinates,[lineString.longitude, lineString.latitude],destinationY1.geometry.coordinates]))
          feature1.setStyle(style)
          this.shpDataLayer.getSource().addFeature(feature1);
          setTimeout(function(){
            that.showBoundingExtent(allCoordinates);//缩放到区域位置
          },200);
        }
      }
    },
    showTaskPosition(geom) {
      if(this.positionDataLayer != null){
        this.positionDataLayer.getSource().clear()
      }
      let featureTmp = new WKT().readFeature(geom);
      let style = this.getPolyonStyle("red");
      featureTmp.setStyle(style);
      //添加矢量数据
      this.positionDataLayer.getSource().addFeature(featureTmp);
    },
    showTaskDataArray(){//显示任务空间数据列表
      if(this.taskDataLayer!=null){
        this.taskDataLayer.getSource().clear();//清空
        let list = this.taskDataArray;
        let allCoordinates = [];
        if(list!=null && list.length>0){
          let dataGeom = list.find(item => item.taskType == '0')
          if(dataGeom){
            let lineString = this.shpDataArray.find(item => item.intensity == '6');
            let featureTmp = new WKT().readFeature(lineString.geom)
            let a = featureTmp.getGeometry().getCoordinates()[0][1]
            let feature = new Feature({
              geometry: new Polygon([featureTmp.getGeometry().getCoordinates()[0][0]])
            })
            let style = this.getPolyonStyle1('red')
            feature.setStyle(style)
            this.taskDataLayer.getSource().addFeature(feature);
          }
          for(let i=0;i<list.length;i++){
            let style = this.getPolyonStyle("orange",null,2);
            let xstmId = list[i].xitmId;//ID
            let geomText = list[i].geom;//空间数据
            if(geomText!=null && geomText!="" && geomText!="POLYGON EMPTY"){
              //空间数据
              let featureTmp = new WKT().readFeature(geomText);
              //设置属性
              featureTmp.setProperties({
                type:"taskPolygon",//类型
                xstmId:xstmId
              });
              featureTmp.setStyle(style);
              //添加矢量数据
              this.taskDataLayer.getSource().addFeature(featureTmp);
              //获取范围
              let extent = featureTmp.getGeometry().getExtent();
              if(extent.length==4){
                //全部经纬度--左下角
                allCoordinates.push([extent[0],extent[1]]);
                //全部经纬度--右上角
                allCoordinates.push([extent[2],extent[3]]);
              }
            }
          }
          let lineString = this.shpDataArray.find(item => item.intensity == '6');
          var bearing = lineString.angle;
          let dataObject = list.find(item => item.taskType == '0')
          let numCount = parseInt(360 / dataObject.groupNumber)
          for(let i = 0;i < dataObject.groupNumber;i++) {
            if(i == 0) {
            }else if(i == dataObject.groupNumber - 1) {
              let num1 = bearing + numCount
              let num2 =  360 + numCount
              if(num1 > num2) {
                bearing = 360 + numCount
              }else{
                bearing = bearing + numCount
              }
            }else{
              bearing = bearing + numCount
            }
            var point = turf.point([lineString.longitude,lineString.latitude]);
            var distance = lineString.shortY;
            var options = {units: 'kilometers'};
            var destination = turf.destination(point, distance, bearing, options);
            let feature = new Feature(new LineString([[lineString.longitude,lineString.latitude],destination.geometry.coordinates]))
            let style = this.getLineStringStyle("blue");
            feature.setStyle(style);
              //添加矢量数据
            this.taskDataLayer.getSource().addFeature(feature);
          }
        }
        this.showBoundingExtent(allCoordinates);//缩放到区域位置
      }
    },
    showSampleDataArray(){//显示抽样点数据列表
      if(this.sampleDataLayer!=null){
        this.sampleDataLayer.getSource().clear();//清空
        let list = this.sampleDataArray;
        if(list!=null && list.length>0){
          console.log("showSampleDataArray");
          for(let i=0;i<list.length;i++){
            // let style = this.getPointStyle("rgba(0,0,255,0.7)","rgba(0,0,255,0.7)");
            let style = this.getPointImgStyle();
            let id = list[i].id;//ID
            let geomText = list[i].geom;//空间数据
            if(geomText!=null && geomText!=""){
              console.log(geomText);
              //空间数据
              let featureTmp = new WKT().readFeature(geomText);
              //设置属性
              featureTmp.setProperties({
                type:"taskSample",//类型
                id:id
              });
              featureTmp.setStyle(style);
              //添加矢量数据
              this.sampleDataLayer.getSource().addFeature(featureTmp);
            }
          }
        }
      }
    },
  }
}

</script>

<style lang="scss" scoped>

</style>